package com.example.home.viewmodel;

import android.util.Log;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.common.component.GameCtrlCom;
import com.example.common.control.ICallback;
import com.example.common.model.GameApiRankResp;
import com.example.common.model.GameResp;

import java.util.ArrayList;
import java.util.List;

public class HomeLeaderboardViewModel extends ViewModel {
    private static final String TAG = "HomeLeaderboardViewModel";
    // TODO: Implement the ViewModel
    public static Integer PN=1;//排行榜当前页面。初始化默认为1
    public static Integer LIMIT=15;//每页加载游戏个数，默认为15
    public static Integer MAX=0;//排行榜游戏总数
    private List<GameResp> games;//游戏数据

    private GameCtrlCom gameCtrlCom;

    private MutableLiveData<String> remainMsg=new MutableLiveData<>();//提示消息
    private MutableLiveData<Boolean> isAdapterLoad=new MutableLiveData<>();//是否路由刷新
    private MutableLiveData<Boolean> isGamesLoad=new MutableLiveData<>();//是否游戏列表更新

    public HomeLeaderboardViewModel(){
        //数据初始化
        initData();
        //首次load
        loadGamesByPN();
    }

    /**
     * 数据初始化
     */
    private void initData(){
        PN=1;
        LIMIT=15;
        games=new ArrayList<>();
        gameCtrlCom=new GameCtrlCom();
    }

    /**
     * 通过页数加载游戏列表
     */
    public void loadGamesByPN(){
        //PN为0时表示已经加载完成
        if(PN==0){
            return;
        }
        //发出请求
        gameCtrlCom.getGameRank(PN, LIMIT, new ICallback() {
            @Override
            public void onSuccess(Object response) {
                GameApiRankResp resp=(GameApiRankResp)response;
                //获取游戏数据
                if(resp.getList()!=null){
                    games.addAll(resp.getList());
                }
                Log.i(TAG, "onSuccess: "+games);
                //排行榜总数
                MAX=resp.getCount();
                //提示adapter需要加载——>fragment中监听
                isAdapterLoad.setValue(true);
            }

            @Override
            public void onFailed(String mes) {
                remainMsg.setValue(mes);
            }
        });
        //下一页递增
        PN++;
    }

    /**
     * 判断排行榜是否加载到最后了
     * @return true为全部加载完成
     */
    public boolean isEnd(){
        if(PN*LIMIT>MAX&&MAX>0){
            return true;
        }
        if(games.size()>=MAX){
            return true;
        }
        return false;
    }

    public MutableLiveData<String> getRemainMsg() {
        return remainMsg;
    }

    public MutableLiveData<Boolean> getIsAdapterLoad() {
        return isAdapterLoad;
    }

    public List<GameResp> getGames() {
        return games;
    }

    public MutableLiveData<Boolean> getIsGamesLoad() {
        return isGamesLoad;
    }
}